<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="info" round :icon="Plus" @click="showTrademarkDialog"
          >添加</el-button
        >
      </div>
    </template>
    <el-table
      :data="trademarkList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column type="index" align="center" label="序号" width="100" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column label="品牌logo">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{ row, $index }">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="修改"
            placement="top"
          >
            <el-button
              type="warning"
              :icon="Edit"
              plain
              @click="editTrademark(row)"
            />
          </el-tooltip>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top"
          >
            <el-button
              type="danger"
              :icon="Delete"
              plain
              @click="delTrademark(row)"
            />
          </el-tooltip>
          <!-- <el-button type="warning" :icon="Edit" plain />
          <el-button type="danger" :icon="Delete" plain /> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        small
        background
        layout="prev, pager, next, jumper,->,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加品牌之对话弹框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${trademark.id ? '修改' : '添加'}品牌`"
    >
      <el-form :model="trademark" :rules="rules" ref="ruleFormRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png 文件，且不超过2M大小
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "Trademark",
}
</script>
<script lang="ts" setup>
import { Plus, Delete, Edit } from "@element-plus/icons-vue"
import { onMounted, ref, reactive } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import type { UploadProps } from "element-plus"
import type { FormInstance, FormRules } from "element-plus" // 验证接口
// 引入接口函数
import {
  reqGetTrademarkList,
  reqSaveTrademarkInfo,
  reqDelTrademarkList,
  reqUpdateTrademarkInfo,
} from "@/api/product/trademark"

// 引入type约束接口
import type { TrademarkListModel } from "@/api/product/model/TrademarkListModel"

// 实现数据校验
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "请添加品牌名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在2到10之间", trigger: "blur" },
  ],
  logoUrl: [
    { required: true, message: "请选择要上传的图片", trigger: "change" },
  ],
})
// 实现添加和修改品牌
let timeId = null as any
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log("submit!")
      if (timeId) clearTimeout(timeId)
      timeId = setTimeout(async () => {
        // console.log(123123)
        if (trademark.id) {
          // 有id则修改品牌
          await reqUpdateTrademarkInfo(trademark)
        } else {
          // 没有id则添加品牌
          await reqSaveTrademarkInfo(trademark)
        }
        ElMessage({
          type: "success",
          message: `${trademark.id ? "修改" : "添加"}成功!`,
        })
      }, 1000)
      // const btnTrademark = async () => {
      //   console.log(123123)

      //   if (trademark.id) {
      //     // 有id则修改品牌
      //     await reqUpdateTrademarkInfo(trademark)
      //   } else {
      //     // 没有id则添加品牌
      //     await reqSaveTrademarkInfo(trademark)
      //   }
      //   ElMessage({
      //     type: "success",
      //     message: `${trademark.id ? "修改" : "添加"}成功!`,
      //   })

      // 关闭弹窗
      dialogFormVisible.value = false
      // 跳转到第一页
      // currentPage.value = 1
      // 重新渲染页面
      getTrademarkList()
    } else {
      // console.log("error submit!", fields)
      ElMessage({
        message: "请安要求填入信息!",
        type: "warning",
      })
    }
  })
}

// 动态读取环境变量中的值
const BASE_URL = import.meta.env.VITE_API_URL

// 加载等待,显示loading
const loading = ref<boolean>(true)

// 定义一些数据
let currentPage = ref<number>(1) // 当前页码
let pageSize = ref<number>(5) // 每页显示的数量
let total = ref<number>(0) // 品牌总数量
let trademarkList = ref<TrademarkListModel>([])
// const imageUrl = ref<string>("") // 图片地址

// 定义一个方法来获取数据
const getTrademarkList = async () => {
  // const result = await reqGetTrademarkList(1, 5)
  const result = await reqGetTrademarkList(currentPage.value, pageSize.value)
  // console.log("品牌管理--->", result)
  trademarkList.value = result.records
  total.value = result.total

  // 隐藏loading效果
  loading.value = false
}
onMounted(() => {
  getTrademarkList()
})

// 修改每页显示条数
const handleSizeChange = (val: number) => {
  loading.value = true
  pageSize.value = val
  currentPage.value = 1
  getTrademarkList()
  loading.value = false
  // console.log(`${val} items per page`)
}
// 单击当前页码实现分页
const handleCurrentChange = (val: number) => {
  // console.log(`current page: ${val}`)
  currentPage.value = val
  loading.value = true
  getTrademarkList()
  loading.value = false
}

// 添加弹窗
const dialogFormVisible = ref<boolean>(false)
const formLabelWidth = "80px"

const initTrademark = () => ({ tmName: "", logoUrl: "" })
const trademark = reactive<TrademarkListModel>(initTrademark())
// const form = reactive<TrademarkListModel>({
//   tmName: "", // 品牌名称
//   logoUrl: "", // logo地址
// })
// 上传图片

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // console.log(response, uploadFile)
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademark.logoUrl = response.data
  // 清除表单验证
  ruleFormRef.value?.clearValidate(["logoUrl"])
}
// 上传图片校验
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("上传图片的格式只能是jepg!")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M,请重新选择!")
    return false
  }
  return true
}

// 清空之前上传的数据
function showTrademarkDialog() {
  Object.assign(trademark, initTrademark())
  delete trademark.id
  // trademark.tmName = ""
  // trademark.logoUrl = ""
  dialogFormVisible.value = true
  // 清除校验规则
  ruleFormRef.value?.clearValidate()
}

// 删除事件
const delTrademark = (row: TrademarkListModel) => {
  // console.log("删除事件--->", row)

  ElMessageBox.confirm(`您真的要删除${row.tmName}吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true
      await reqDelTrademarkList(row.id as number)
      ElMessage({
        type: "success",
        message: "删除成功",
      })
      // 重新渲染页面
      // 判断当前页面的是否还有数据,如果有则留在当前页码,如果没有,则跳转到上一个页码
      currentPage.value =
        trademarkList.value.length > 1
          ? currentPage.value
          : currentPage.value - 1
      getTrademarkList()
      loading.value = false
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      })
    })
}

// 修改弹框
const editTrademark = (row: TrademarkListModel) => {
  Object.assign(trademark, row)
  dialogFormVisible.value = true
  // 清除校验规则
  ruleFormRef.value?.clearValidate()
}
</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

/* 上传图片 */
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-input {
  width: 70%;
}
/* 删除弹框 */
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style>
.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>
